package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckLogin",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路劲匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        //log.info("拦截的q请求是:{}",requestURI);

        //可以放行的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //2.判断是可以放行，路径属于放行目录则放行
        if (checkUri(urls, requestURI)){
            //log.info("该路径 {} 不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //3-1.判断后台管理端登陆状态
        if (request.getSession().getAttribute("employee") != null){
            //log.info("用户已登录，用户的id是{}",request.getSession().getAttribute("employee"));
            Long empId = (Long) request.getSession().getAttribute("employee");
            //将Id放入ThreadLocal中
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        //3-2.判断移动端登陆状态
        if (request.getSession().getAttribute("user") != null){
            //log.info("用户已登录，用户的id是{}",request.getSession().getAttribute("employee"));
            Long userId = (Long) request.getSession().getAttribute("user");
            //将Id放入ThreadLocal中
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //log.info("用户未登录");
        //4.如果未登录,响应未登录结果,通过输出流的方式响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean checkUri(String[] uriString,String requestURI){
        for (String s : uriString) {
            boolean match = PATH_MATCHER.match(s, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
